import Vapor
import Fluent
import FluentMySQLDriver
import QueuesFluentDriver
// configures your application
public func configure(_ app: Application) async throws {
    print("开始配置!!!")
    let privateKey = """
-----BEGIN PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgr1ZX4hHIyD2MGBd8
YAW30V9Ij05oAuIuCRjDwsop2PWgCgYIKoZIzj0DAQehRANCAATBH45Yyl5obs+3
gGzOEK7/cdG30Y7+ui12zTxPrd1+w635U+D2bO/X0bTNiHp2Opa9+swBVozY8K1l
jtMqP8lR
-----END PRIVATE KEY-----
"""
    let sandBoxStr = Environment.get("SanxBox") ?? "1"
    let sandBox = sandBoxStr == "1"
    let apnsConfig = APNSConfiguration(keyID: "ZL27MUDNCP", teamID: "886D7HSASS", privateKey: privateKey, bundleID: "com.xusi1508tracker.www", isSandbox: sandBox)
    app.apns = APNSClient(app: app, configuration: apnsConfig)
    var certPaths: [String] = []
    for i in 0 ..< 3 {
        let certPath = app.directory.publicDirectory + "\(i).cer"
        certPaths.append(certPath)
    }
    app.appstore = AppStoreService(certPaths: certPaths)
    app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
    app.routes.defaultMaxBodySize = "50mb"
    // register routes
    let dbhost = Environment.get("DATABASE_HOST") ?? "localhost"
    let dbuser = Environment.get("DATABASE_USERNAME") ?? "root"
    let dbpass = Environment.get("DATABASE_PASSWORD") ?? "enghou123"
    let dbname = Environment.get("DATABASE_NAME") ?? "location_tracker"
    app.databases.use(.mysql(
        hostname: dbhost,
        username: dbuser,
        password: dbpass,
        database: dbname
    ), as: .mysql)
    app.queues.use(.fluent())
    app.migrations.add(JobModelMigration())
    app.migrations.add(UserModelMigration())
    app.migrations.add(LocationModelMigration())
    app.migrations.add(TaskModelMigration())
    app.migrations.add(GroupModelMigration())
    app.migrations.add(GroupMemberModelMigration())
    app.migrations.add(InviteCodeModelMigration())
    app.migrations.add(FeedbackModelMigration())
    app.migrations.add(APNSModelMigration())
    app.migrations.add(JSBundleModelMigration())
    app.migrations.add(SubscriptionRecordModelMigration())
    app.migrations.add(OfflineLocationFetchRequestMigration())
    app.queues.add(EndWatchDriveJob())
    app.queues.add(PushJob())
    try await app.autoMigrate()
    try app.queues.startInProcessJobs(on: .default)
    try routes(app)
    do {
        app.imClient = IMManager(application: app)
        try await app.imClient.getAccessToken()
    } catch {
        print(error)
    }
    print("启动成功")
}
